import pika
import json

# Connection parameters
credentials = pika.PlainCredentials('XuYixuan', 'Xyx20040422')
connection = pika.BlockingConnection(pika.ConnectionParameters('82.156.163.134', 5672, '/', credentials))
channel = connection.channel()

# Declare queues
channel.queue_declare(queue='text_stream')
channel.queue_declare(queue='word_counts')

def callback(ch, method, properties, body):
    print("Received message:", body)  # Debugging statement
    text = body.decode('utf-8')
    word_counts = {}
    for word in text.split():
        word_counts[word] = word_counts.get(word, 0) + 1
    print("Word counts:", word_counts)  # Debugging statement
    channel.basic_publish(exchange='',
                          routing_key='word_counts',
                          body=json.dumps(word_counts).encode('utf-8'))
    print("Published message to word_counts queue")  # Debugging statement

# Consume messages
channel.basic_consume(queue='text_stream', on_message_callback=callback, auto_ack=True)

print('Waiting for messages. To exit press CTRL+C')
callback(None, None, None, b'hello world')
channel.start_consuming()